#!/usr/bin/env groovy

def call(String techStack = '') {
  echo "======================RUN DOCKER ON (TECHSTACK:${techStack})============================="

  sh label: 'DOCKER-LOGIN', returnStdout: true, script: 
        '''    
         echo "login harbor ${HARBOR}"        
         
         loginCmd="docker login --username=${HARBOR_ACCESS_KEY_USR} --password=${HARBOR_ACCESS_KEY_PSW} ${HARBOR}"
         sshpass -p "${SERVER_ACCESS_KEY_PSW}" ssh -o StrictHostKeyChecking=no ${SERVER_ACCESS_KEY_USR}@${DEPLOY_SERVER} "$loginCmd"
        ''' 
     try
     {
        if ( techStack == 'vue') {
         sh label: 'DOCKER-RUN', returnStdout: true, script: 
          '''      
         echo "stop/clean ${DOCKER_NAME} docker container on ${DEPLOY_SERVER}"       
         cleanCmd="docker rm -f ${DOCKER_NAME} > /dev/null 2>&1 && echo 'removed container' || echo 'nothing to remove' ; \\
                   docker rmi --force \\`docker images | grep ${DOCKER_NAME} | awk \'{print \\$3}\' \\` > /dev/null 2>&1&& echo 'removed images' || echo 'nothing to remove' "
         sshpass -p "${SERVER_ACCESS_KEY_PSW}" ssh -o StrictHostKeyChecking=no ${SERVER_ACCESS_KEY_USR}@${DEPLOY_SERVER} "$cleanCmd"

         echo "deploy image: ${HARBOR}/${PROJECT_NAME}/${DOCKER_NAME}:${VERSION_NUMBER} to ${DEPLOY_SERVER}"                 
         
         # change ports for different app
         runCmd="docker pull ${HARBOR}/${PROJECT_NAME}/${DOCKER_NAME}:${VERSION_NUMBER}; \
               docker run -d --name ${DOCKER_NAME} -p 8088:80 --restart=always ${EXTRA_PARAMETER} ${HARBOR}/${PROJECT_NAME}/${DOCKER_NAME}:${VERSION_NUMBER}"
         echo "runCmd: $runCmd"
         sshpass -p "${SERVER_ACCESS_KEY_PSW}" ssh -o StrictHostKeyChecking=no ${SERVER_ACCESS_KEY_USR}@${DEPLOY_SERVER} "$runCmd"
        
        ''' 
        } 
        else if (techStack == 'springboot') {           
           sh label: 'DOCKERCOMPOSE-YAML-COPY', returnStdout: true, script: 
           '''      
            echo "start to copy .env and docker-compose.yml to ${DEPLOY_SERVER}"
            sshpass -p "${SERVER_ACCESS_KEY_PSW}" ssh -o StrictHostKeyChecking=no ${SERVER_ACCESS_KEY_USR}@${DEPLOY_SERVER} "mkdir -p /home/user/deploy-${PROJECT_NAME} "
            sshpass -p "${SERVER_ACCESS_KEY_PSW}" scp docker-compose.yml  ${SERVER_ACCESS_KEY_USR}@${DEPLOY_SERVER}:/home/user/deploy-${PROJECT_NAME} 
            sshpass -p "${SERVER_ACCESS_KEY_PSW}" scp docker-compose-middleware.yml  ${SERVER_ACCESS_KEY_USR}@${DEPLOY_SERVER}:/home/user/deploy-${PROJECT_NAME} 
           ''' 

           sh label: 'DOCKERCOMPOSE-middleware-RUN', returnStdout: true, script: 
           '''            
            echo  "start middleware services, eg. mysql, redis.."

            runCmd="cd /home/user/deploy-${PROJECT_NAME}; \\
            exist=\\`docker-compose -f docker-compose-middleware.yml -p middleware ps|grep Up\\`&&echo "\\$exist";if [ -n \\"\\$exist\\" ]; then echo \'skipping...middleware service is running.\'; \\
            else echo \'middleware service NOT EXIST; start middleware services....\';\\
            docker network create middleware_default > /dev/null 2>&1; \\
            docker-compose -f docker-compose-middleware.yml -p middleware down; \\
            docker-compose -f docker-compose-middleware.yml -p middleware up -d; fi"

            sshpass -p "${SERVER_ACCESS_KEY_PSW}" ssh -o StrictHostKeyChecking=no ${SERVER_ACCESS_KEY_USR}@${DEPLOY_SERVER} "$runCmd"
            '''

           sh label: 'DOCKERCOMPOSE-business-RUN', returnStdout: true, script: 
           '''      
            echo "start to run docker-compose services..."\

            runCmd="cd /home/user/deploy-${PROJECT_NAME}; \
            docker-compose -f docker-compose.yml -p ${DOCKER_NAME} ps&&sleep 10; \
            docker-compose -f docker-compose.yml -p ${DOCKER_NAME} down; \
            for i in $(cat docker-compose.yml |grep 'image'|cut -d ':' -f 2|tr "\n" " "); do docker rmi -f \\`docker images|grep \\$i |awk \'{print \\$3}\' \\` > /dev/null 2>&1&& echo 'removed images' || echo 'nothing to remove'; done ; \
            TAG=${VERSION_NUMBER} docker-compose -f docker-compose.yml -p ${DOCKER_NAME} up -d;"
            
            sshpass -p "${SERVER_ACCESS_KEY_PSW}" ssh -o StrictHostKeyChecking=no ${SERVER_ACCESS_KEY_USR}@${DEPLOY_SERVER} "$runCmd"
            '''                   
        } else{
           throw new RuntimeException("NotImplementedException; ${techStack} IS NOT SUPPORT NOW")     }
 } 
    catch(Exception ex) {
         println("Catching the exception,");
         println(ex.toString());
         println(ex.getMessage());
         println(ex.getStackTrace());  
         currentBuild.result = 'FAILURE'
      }
       finally {
        echo "currentBuild.result ${currentBuild.result}"          
        if (currentBuild.result != 'FAILURE') {           
           echo 'This did work!'
       }
   }
      echo "===================================DONE=====================================" 
}
